/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.clooud.modulos.eventos.bean;

import com.clooud.modulos.eventos.controller.EventoController;
import com.clooud.modulos.eventos.model.EventoModel;
import com.clooud.util.ec.EC;
import com.clooud.util.pmf.PMF;
import com.google.appengine.api.datastore.KeyFactory;
import java.io.Serializable;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.jdo.PersistenceManager;

/**
 * @author selvino
 * @since 26/03/2011
 */
@ManagedBean
@ViewScoped
public class EventoBean implements Serializable {

    /** Cria uma nova instancia do ManagedBean */
    public EventoBean() {
    }

    private EventoModel evento;

    /**
     * @return the evento
     */
    public EventoModel getEvento() {
        if (evento == null) {
            Map<String, String> parametros = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
            if (parametros.containsKey("evento")) {
                String eventoKey = parametros.get("evento");
                evento = EventoController.getEventoFromKey(KeyFactory.stringToKey(eventoKey));
            } else {
                evento = EventoController.createEvento();
            }
        }
        return evento;
    }

    /**
     * @param evento the evento to set
     */
    public void setEvento(EventoModel evento) {
        this.evento = evento;
    }


    public void salvar() {
        PersistenceManager pm = PMF.getPersistenceManager();
        try {
            pm.makePersistent(evento);
            EC.redirect("cadastro_evento.jsf?evento=" + KeyFactory.keyToString(evento.getKey()));
        } finally {
            pm.close();
        }
    }
}
